package com.villaday.idf.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Environment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.adapter.BournFiltersSortAdapter;
import com.villaday.idf.adapter.BournFiltersTypeAdapter;
import com.villaday.idf.adapter2.FindMinSulAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.CustomPopupWindow;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.custom.RangeSeekBar.OnRangeChangedListener;
import com.villaday.idf.custom.RangeSeekBar.RangeSeekBar;
import com.villaday.idf.model.Houses_filtersEntity;
import com.villaday.idf.model.VillagesEntity;
import com.villaday.idf.model2.Find_House_minsu_listEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.ToastUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

public class SearchBournForHouseActivity extends BaseActivity implements OkHttpUtil.OnDataListener, View.OnClickListener, OnAdapterCallbackListener, AbsRecyclerViewAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, BaseDialog.OnItemClickListener, TextWatcher {


    @BindView(R.id.tv_default)
    TextView tvDefault;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.rv_dataList)
    RecyclerView rvDataList;
    @BindView(R.id.ll_addrSort)
    View ll_addrSort;

    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.toolbar_searchBox)
    public AutoCompleteTextView autoTextView;
    @BindView(R.id.img_delete_search)
    ImageView imgDeleteSearch;

    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 10;

    private String villageId = "";//小区ID
    private String city = "";//城市名称(如:深圳)
    private String area = "";//区县名称(如:盐田区)
    private String types = "";//房源类型(0:别墅客栈,1:特色公寓,3:轰趴场馆,4:度假村,空值:全部)
    private String minPrice = "0";//最低价格
    private String maxPrice = "0";//最高价格
    private String minPeople = "0";//最低人数
    private String maxPeople = "0";//最高人数
    private String facilities = "";//设施选项(多项以逗号分隔)(如:泳池,温泉...)
    private String sortBy = "";//排序规则(price_asc:价格最高,price_desc:价格最低,空值:默认排序)

    private String scenicSpotId = "";
    private String businesId = "";
    private String stationId = "";
    private String subwayLineId = "";
    private String collegeId = "";

    private int minPriceCurrent = 0;
    private int maxPriceCurrent = 0;

    private int onChangeminPriceCurrent = 0;
    private int onChangemaxPriceCurrent = 0;

    private int peoplesCurrent = 0;
    private int onChangePeoplesCurrent = 0;

    private String words = "";





    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();
    private VillagesEntity villagesEntity;

    private List<Find_House_minsu_listEntity.BodyEntity.ListEntity> data = new ArrayList();
    private FindMinSulAdapter bournDeticalAdapter;
    private Houses_filtersEntity houses_filtersEntity;
    private int currentSortPosition = -1;// 默认排序
    private int currentTypePosition = -1;// 房源类型

    private BournFiltersSortAdapter bournFiltersSortAdapter;
    private BournFiltersTypeAdapter bournFiltersTypeAdapter;
    private RangeSeekBar sideBar;
    Set<Integer> facilitiespositionS = new HashSet<Integer>();//设备选中的position  集合
    private TagAdapter<Houses_filtersEntity.BodyEntity.FiltersEntity.FacilitiesEntity> tagAdapter;
    private TagFlowLayout idFlowlayout;
    private View currentView;
    private StatusLayoutManager statusLayoutManager;
    private CharSequence[] tickMarkTextArray;

    @Override
    protected int getViewResId() {
        return R.layout.activity_search_bourn_for_house;
    }

    @Override
    protected void init() {
        words=getIntent().getStringExtra("text");
        autoTextView.setHint(getIntent().getStringExtra("text"));
        autoTextView.addTextChangedListener(this);
        statusLayoutManager = setupDefaultStatusLayoutManager(ll, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");

                loadData();
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });
        //透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        StatusBarUtil.setLightMode(this);


        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getFragmentManager(), "loading");
        villageId = getIntent().getStringExtra("villageId");
        city = getIntent().getStringExtra("city");
        area = getIntent().getStringExtra("area");

        scenicSpotId = getIntent().getStringExtra("scenicSpotId");
        businesId = getIntent().getStringExtra("businesId");
        stationId = getIntent().getStringExtra("stationId");
        subwayLineId = getIntent().getStringExtra("subwayLineId");
        collegeId = getIntent().getStringExtra("collegeId");


        rvDataList.setLayoutManager(new LinearLayoutManager(this));
        bournDeticalAdapter = new FindMinSulAdapter(this, this, this);
        rvDataList.setAdapter(bournDeticalAdapter);

        rvDataList.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 8)));
        bournDeticalAdapter.setOnItemClickListener(this);
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        bournDeticalAdapter.setEmptyView(R.layout.empty_tips);
        bournDeticalAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");

    }

    @OnEditorAction(R.id.toolbar_searchBox)
    public boolean onEditAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            //ToastUtil.initToast(this, "hhhh");
            PhoneUtil.hideKeyboard(v);
            CharSequence text = v.getText();
            if (!TextUtils.isEmpty(text)) {
                minPriceCurrent = 0;
                if (tickMarkTextArray!=null&&tickMarkTextArray.length>=1){
                    maxPriceCurrent = tickMarkTextArray.length - 1;

                }
                peoplesCurrent = 0;

                onChangePeoplesCurrent = 0;
                facilitiespositionS.clear();
                if (tagAdapter!=null){
                    tagAdapter.setSelectedList(facilitiespositionS);

                }

                words=text.toString();
                loadData();
            }


            return true;
        }
        return false;
    }

    @Override
    protected void loadData() {
        //OkHttpUtil.getJSON(this, String.format(Constant.URL.villages, villageId), this);

        getHouseList();
    }

    private void getHouseList() {
        //价格
        if (houses_filtersEntity != null &&
                houses_filtersEntity.getBody() != null &&
                houses_filtersEntity.getBody().getFilters() != null &&
                houses_filtersEntity.getBody().getFilters().getPrices() != null) {
            minPrice = houses_filtersEntity.getBody().getFilters().getPrices().get(minPriceCurrent).getName();

            if (maxPriceCurrent == houses_filtersEntity.getBody().getFilters().getPrices().size() - 1) {
                maxPrice = "0";

            } else {
                maxPrice = houses_filtersEntity.getBody().getFilters().getPrices().get(maxPriceCurrent).getName();


            }
        }
        //人数
        if (houses_filtersEntity != null &&
                houses_filtersEntity.getBody() != null &&
                houses_filtersEntity.getBody().getFilters() != null &&
                houses_filtersEntity.getBody().getFilters().getPeoples() != null) {
            minPeople = houses_filtersEntity.getBody().getFilters().getPeoples().get(peoplesCurrent).getId();


        }
        //人数
        if (houses_filtersEntity != null &&
                houses_filtersEntity.getBody() != null &&
                houses_filtersEntity.getBody().getFilters() != null &&
                houses_filtersEntity.getBody().getFilters().getFacilities() != null) {

            facilities="";

            for (Integer str : facilitiespositionS) {
                facilities = facilities + houses_filtersEntity.getBody().getFilters().getFacilities().get(str).getId() + ",";
            }
            if (!TextUtils.isEmpty(facilities)) {
                facilities = facilities.substring(0, facilities.length() - 1);
            }
        }


        Map<String, String> map = new HashMap<>();
        map.put("villageId", villageId );
        map.put("city", city );
        map.put("area", area );
        map.put("types", types);
        map.put("minPrice", minPrice );
        map.put("maxPrice", maxPrice );
        map.put("minPeople", minPeople );
        map.put("maxPeople", maxPeople );
        map.put("facilities", facilities );
        map.put("sortBy", sortBy );
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");

        map.put("scenicSpotId", scenicSpotId );
        map.put("businesId", businesId );
        map.put("stationId", stationId );
        map.put("subwayLineId", subwayLineId );
        map.put("collegeId", collegeId );
        map.put("words", words );



        OkHttpUtil.getJSON(this, Constant.URL.houses_list, map, this);

    }

    @OnClick({R.id.img_delete_search,R.id.tv_default, R.id.tv_type, R.id.tv_more})
    public void onViewClicked(View view) {
        if (view.getId()==R.id.img_delete_search){
            autoTextView.setText("");
            imgDeleteSearch.setVisibility(View.INVISIBLE);
        }else {
            if (houses_filtersEntity == null || houses_filtersEntity.getBody() == null || !"200".equals(houses_filtersEntity.getCode())) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");
                OkHttpUtil.getJSON(this, Constant.URL.houses_filters, this);
                currentView = view;

            } else {
                getMore(view);
            }
        }


    }

    private void getMore(View view) {
        switch (view.getId()) {
            case R.id.tv_default: {//默认排序
                tvDefault.setSelected(true);

                final CustomPopupWindow builder = new CustomPopupWindow.Builder().setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setOutSideCancel(true)
                        .setContext(this)
                        .setContentView(R.layout.popu_bourn_head_chose_addr_sort)
                        .setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                tvDefault.setSelected(false);
                            }
                        })
                        .builder();

                builder.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        builder.dismiss();
                    }
                });


                builder.showAsLaction(ll_addrSort, Gravity.BOTTOM, 0, 0);


                RecyclerView rvAddr = (RecyclerView) builder.getItemView(R.id.rv_addr_sort);
                rvAddr.setLayoutManager(new LinearLayoutManager(this));
                if (bournFiltersSortAdapter == null) {
                    bournFiltersSortAdapter = new BournFiltersSortAdapter(this);

                }
                if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
                    bournFiltersSortAdapter.setData(houses_filtersEntity.getBody().getSorts());
                }
                rvAddr.setAdapter(bournFiltersSortAdapter);

                rvAddr.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 8)));
                bournFiltersSortAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null) {
                            houses_filtersEntity.getBody().getSorts().get(position).setCheck(!houses_filtersEntity.getBody().getSorts().get(position).isCheck());

                            if (currentSortPosition != -1 && currentSortPosition != position) {
                                houses_filtersEntity.getBody().getSorts().get(currentSortPosition).setCheck(!houses_filtersEntity.getBody().getSorts().get(currentSortPosition).isCheck());

                            }
                            if (houses_filtersEntity.getBody().getSorts().get(position).isCheck()) {
                                sortBy = houses_filtersEntity.getBody().getSorts().get(position).getId();

                                tvDefault.setText(houses_filtersEntity.getBody().getSorts().get(position).getName());
                                currentSortPosition = position;
                            } else {
                                tvDefault.setText("默认排序");

                                sortBy = "";
                                currentSortPosition = -1;

                            }
                            bournFiltersSortAdapter.notifyDataSetChanged();
                            loadingDialog = LoadingDialog.newInstance("加载中");
                            loadingDialog.show(getFragmentManager(), "loading");
                            onRefresh();
                        }

                    }
                });
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
                bournFiltersSortAdapter.setEmptyView(R.layout.empty_tips);
                bournFiltersSortAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");

            }
                /*ChooseDefalutDialog chooseDefalutDialog = ChooseDefalutDialog.newInstance();
                chooseDefalutDialog.show(getFragmentManager());*/

            break;
            case R.id.tv_type: {//房源类型
                tvType.setSelected(true);
                final CustomPopupWindow builder1 = new CustomPopupWindow.Builder().setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setOutSideCancel(true)
                        .setContext(this)
                        .setContentView(R.layout.popu_bourn_head_chose_addr_sort)
                        .setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                tvType.setSelected(false);
                            }
                        })
                        .builder();

                builder1.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        builder1.dismiss();
                    }
                });


                builder1.showAsLaction(ll_addrSort, Gravity.BOTTOM, 0, 0);

                RecyclerView rvAddr = (RecyclerView) builder1.getItemView(R.id.rv_addr_sort);
                rvAddr.setLayoutManager(new LinearLayoutManager(this));
                if (bournFiltersTypeAdapter == null) {
                    bournFiltersTypeAdapter = new BournFiltersTypeAdapter(this);

                }
                if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
                    bournFiltersTypeAdapter.setData(houses_filtersEntity.getBody().getTypes());
                }
                rvAddr.setAdapter(bournFiltersTypeAdapter);

                rvAddr.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 8)));
                bournFiltersTypeAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null) {
                            houses_filtersEntity.getBody().getTypes().get(position).setCheck(!houses_filtersEntity.getBody().getTypes().get(position).isCheck());

                            if (currentTypePosition != -1 && currentTypePosition != position) {
                                houses_filtersEntity.getBody().getTypes().get(currentTypePosition).setCheck(!houses_filtersEntity.getBody().getTypes().get(currentTypePosition).isCheck());

                            }
                            if (houses_filtersEntity.getBody().getTypes().get(position).isCheck()) {
                                types = houses_filtersEntity.getBody().getTypes().get(position).getId();

                                tvType.setText(houses_filtersEntity.getBody().getTypes().get(position).getName());
                                currentTypePosition = position;
                            } else {
                                tvType.setText("房源类型");

                                types = "";
                                currentTypePosition = -1;

                            }
                            bournFiltersTypeAdapter.notifyDataSetChanged();
                            loadingDialog = LoadingDialog.newInstance("加载中");
                            loadingDialog.show(getFragmentManager(), "loading");
                            onRefresh();
                        }

                    }
                });
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
                bournFiltersTypeAdapter.setEmptyView(R.layout.empty_tips);
                bournFiltersTypeAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");

            }
            break;
            case R.id.tv_more: {//更多筛选
                tvMore.setSelected(true);
                final CustomPopupWindow builder2 = new CustomPopupWindow.Builder().setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setOutSideCancel(true)
                        .setContext(this)
                        .setContentView(R.layout.popu_choose_more)
                        .setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                tvMore.setSelected(false);
                            }
                        })
                        .builder();

                builder2.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        builder2.dismiss();
                    }
                });


                if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
                    builder2.showAsLaction(ll_addrSort, Gravity.BOTTOM, 0, 0);

                    //价格
                    sideBar = (RangeSeekBar) builder2.getItemView(R.id.sideBar);
                    sideBar.setTypeface(Typeface.DEFAULT_BOLD);
                    sideBar.getLeftSeekBar().setTypeface(Typeface.DEFAULT_BOLD);
                    sideBar.setOnRangeChangedListener(new OnRangeChangedListener() {
                        @Override
                        public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                            onChangeminPriceCurrent = (int) leftValue;
                            onChangemaxPriceCurrent = (int) rightValue;
                        }

                        @Override
                        public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

                        }

                        @Override
                        public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

                        }
                    });
                    sideBar.setTickMarkNumber(houses_filtersEntity.getBody().getFilters().getPrices().size() - 1);
                    tickMarkTextArray = new CharSequence[houses_filtersEntity.getBody().getFilters().getPrices().size()];
                    sideBar.setRangeInterval(100f / (houses_filtersEntity.getBody().getFilters().getPrices().size() - 1));
                    for (int i = 0; i < houses_filtersEntity.getBody().getFilters().getPrices().size(); i++) {
                        tickMarkTextArray[i] = houses_filtersEntity.getBody().getFilters().getPrices().get(i).getName();
                    }
                    sideBar.setTickMarkTextArray(tickMarkTextArray);
                    if (maxPriceCurrent == 0) {
                        maxPriceCurrent = tickMarkTextArray.length - 1;
                        onChangemaxPriceCurrent = maxPriceCurrent;

                    }
                    sideBar.setValue(minPriceCurrent, maxPriceCurrent);


                    //重置按钮

                    builder2.getItemView(R.id.tv_reset).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            minPriceCurrent = 0;
                            maxPriceCurrent = tickMarkTextArray.length - 1;
                            peoplesCurrent = 0;
                            onChangePeoplesCurrent = 0;
                            facilitiespositionS.clear();
                            tagAdapter.setSelectedList(facilitiespositionS);

                            loadingDialog = LoadingDialog.newInstance("加载中");
                            loadingDialog.show(getFragmentManager(), "loading");
                            onRefresh();
                            builder2.dismiss();
                        }
                    });


                    //确定按钮

                    builder2.getItemView(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            minPriceCurrent = onChangeminPriceCurrent;
                            maxPriceCurrent = onChangemaxPriceCurrent;
                            peoplesCurrent = onChangePeoplesCurrent;
                            facilitiespositionS.clear();
                            facilitiespositionS.addAll(idFlowlayout.getSelectedList());
                            loadingDialog = LoadingDialog.newInstance("加载中");
                            loadingDialog.show(getFragmentManager(), "loading");
                            onRefresh();
                            builder2.dismiss();
                        }
                    });
                    // 出行人数
                    final TextView peoples = (TextView) builder2.getItemView(R.id.tv_peoples);
                    peoples.setText(houses_filtersEntity.getBody().getFilters().getPeoples().get(peoplesCurrent).getName());
                    onChangePeoplesCurrent = peoplesCurrent;
                    // 出行人数减
                    builder2.getItemView(R.id.img_minus).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (onChangePeoplesCurrent == 0) {
                                onChangePeoplesCurrent = houses_filtersEntity.getBody().getFilters().getPeoples().size() - 1;

                            } else {
                                onChangePeoplesCurrent = onChangePeoplesCurrent - 1;

                            }
                            peoples.setText(houses_filtersEntity.getBody().getFilters().getPeoples().get(onChangePeoplesCurrent).getName());

                        }
                    });
                    // 出行人数加

                    builder2.getItemView(R.id.img_plus).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (onChangePeoplesCurrent == houses_filtersEntity.getBody().getFilters().getPeoples().size() - 1) {
                                onChangePeoplesCurrent = 0;

                            } else {
                                onChangePeoplesCurrent = onChangePeoplesCurrent + 1;

                            }
                            peoples.setText(houses_filtersEntity.getBody().getFilters().getPeoples().get(onChangePeoplesCurrent).getName());

                        }
                    });

                    //设施
                    idFlowlayout = (TagFlowLayout) builder2.getItemView(R.id.id_flowlayout);


                    tagAdapter = new TagAdapter<Houses_filtersEntity.BodyEntity.FiltersEntity.FacilitiesEntity>(houses_filtersEntity.getBody().getFilters().getFacilities()) {
                        @Override
                        public View getView(FlowLayout parent, int position, Houses_filtersEntity.BodyEntity.FiltersEntity.FacilitiesEntity s) {
                            TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tv_20_have_sheshi,
                                    idFlowlayout, false);
                            tv.setText(s.getName());

                            return tv;
                        }
                    };
                    idFlowlayout.setAdapter(tagAdapter);
                    if (facilitiespositionS.size() != 0) {

                        tagAdapter.setSelectedList(facilitiespositionS);
                    }


                    idFlowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                        @Override
                        public boolean onTagClick(View view, int position, FlowLayout parent) {

                            return true;
                        }
                    });
                }


            }
            break;

        }


    }


    @Override
    public void onResponse(String url, String json) {
        if (statusLayoutManager != null) {
            statusLayoutManager.showSuccessLayout();

        }
        if (String.format(Constant.URL.villages, villageId).equals(url)) {
            LogeUtil.e("villages", json);
            villagesEntity = gson.fromJson(json, VillagesEntity.class);
            if (villagesEntity.getBody() != null && "200".equals(villagesEntity.getCode())) {
                initView();
            }
        } else if (Constant.URL.houses_list.equals(url)) {
            dismissLoading();
            LogeUtil.e("houses_list", json);
            Find_House_minsu_listEntity houses_listEntity = gson.fromJson(json, Find_House_minsu_listEntity.class);
            removeLoadingItem();
            if (pageNo == 1) {
                data.clear();
            }

            if ("200".equals(houses_listEntity.getCode()) && houses_listEntity.getBody() != null) {
                data.addAll(houses_listEntity.getBody().getList());
                if (houses_listEntity.getBody().isHasNext()) {
                    data.add(new Find_House_minsu_listEntity.BodyEntity.ListEntity(1));
                    nextIndex = pageNo + 1;

                } else {
                    addBaseLine();
                }

            } else {
                addBaseLine();
            }
            bournDeticalAdapter.setData(data);
        } else if (Constant.URL.houses_filters.equals(url)) {
            dismissLoading();
            LogeUtil.e("houses_filters", json);
            houses_filtersEntity = gson.fromJson(json, Houses_filtersEntity.class);

            if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
                getMore(currentView);

            }

        }
    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new Find_House_minsu_listEntity.BodyEntity.ListEntity(2));
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void initView() {

    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (statusLayoutManager != null) {

            statusLayoutManager.showErrorLayout();
        }
        ToastUtil.initToast(this,"网络错误");
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }


    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tuiguang://推荐
                Intent intent = new Intent(this, HouseDetailsActivityFor3.class);
                intent.putExtra("type", 1);
                intent.putExtra("houseId", data.get((Integer) view.getTag()).getId());
                intent.putExtra("presellProduct", false);

                intent.putExtra("brokerAge", data.get((Integer) view.getTag()).getBrokerAgeAmountValue());
                intent.putExtra("persellId", data.get((Integer) view.getTag()).getId());
                startActivity(intent);
                /*loadingDialog = LoadingDialog.newInstance("跳转中");
                loadingDialog.show(getFragmentManager(), "loading");
                String villageId = data.get((Integer) view.getTag()).getId();

                OkHttpUtil.getJSON(this, String.format(Constant.URL.vips_villages_posters, villageId), new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        if (!TextUtils.isEmpty(json)) {
                            dismissLoading();
                            Material_postersEntity material_postersEntity = gson.fromJson(json, Material_postersEntity.class);
                            if ("200".equals(material_postersEntity.getCode())) {
                                LogeUtil.e("material_posters" + json);
                                ErWeiMaDialog erWeiMaDialog = ErWeiMaDialog.newInstance(material_postersEntity.getBody().getPoster());
                                erWeiMaDialog.show(getFragmentManager());

                                erWeiMaDialog.setOnItemClickListener(SearchBournForHouseActivity.this);
                            } else {
                                ToastUtil.initToast(SearchBournForHouseActivity.this, material_postersEntity.getMsg());
                            }
                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });*/

                break;
        }
    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getHouseList();
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent = new Intent(this, HouseDetailsActivityFor3.class);
        intent.putExtra("type", 0);
        intent.putExtra("houseId", data.get(position).getId());
        intent.putExtra("presellProduct", false);

        intent.putExtra("brokerAge", data.get(position).getBrokerAgeAmountValue());
        intent.putExtra("persellId", data.get(position).getId());
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getHouseList();
    }


    @OnClick({R.id.toolbar_back, })
    public void onViewClicked2(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                onBackPressed();
                break;

        }
    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {

            case R.id.tv_wx: {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(SearchBournForHouseActivity.this,0, images,images.get(images.size()-1),"");

            }
            break;
            case R.id.tv_pyq: {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(SearchBournForHouseActivity.this,1, images,images.get(images.size()-1),"");

            }
            break;
            case R.id.tv_save: {
                saveImageToSdCard(this, (String) v.getTag(), true);
                ToastUtil.initToast(this, "保存成功");
            }
            break;
        }
    }



    //根据网络图片url路径保存到本地
    public static final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    public static String IMAGE_NAME = "iv_share_";
    public static int i = 0;

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s)){
            imgDeleteSearch.setVisibility(View.INVISIBLE);

        }else {
            imgDeleteSearch.setVisibility(View.VISIBLE);

        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
